package com.penjin.android.activity.shenpi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinCompany;
import com.penjin.android.domain.PenjinStaff;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.domain.PenjinWorkflowForm;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.ScreenUtils;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的审批
 * Created by Administrator on 2016/3/21.
 */
public class MyShenpiActivity extends Activity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {

    PenjinUser user;
    PenjinCompany company;
    PenjinStaff staff;

    boolean isListLoaded = false;

    SwipeRefreshLayout swipeRefreshLayout;
    TitleBarView titleBarView;
    ListView listView;
    ShenpiAdapter adapter;
    HttpService httpService;
    TextHttpResponseHandler handler;
    CustomProgressDialog progressDialog;
    List<PenjinWorkflowForm> dataList = new ArrayList<PenjinWorkflowForm>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_my_shenpi);
        initData(savedInstanceState);
        initView();
        initHttp();
    }

    private void initData(Bundle savedInstanceState) {
        UserService userService = UserService.getInstance(this.getApplicationContext());
        user = userService.getCurrentUser();
        company = userService.getCurrentCompany();
        staff = userService.getCurrentStaff();
    }

    private void initView() {
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeColors(new int[]{getResources().getColor(R.color.aquamarine), getResources().getColor(R.color.pink), getResources().getColor(R.color.greenyellow)});
        listView = (ListView) findViewById(R.id.listView);
        adapter = new ShenpiAdapter(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(MyShenpiActivity.this,MyShenpiDetailActivity.class);
                intent.putExtra("bill",dataList.get(position));
                startActivity(intent);
            }
        });
    }

    private void initHttp() {
        httpService = HttpService.getInstance(this.getApplicationContext());
        handler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                swipeRefreshLayout.setRefreshing(false);
                progressDialog.dismiss();
                if (s != null) {
                    System.out.println(s);
                    ToastHelper.showServerError(MyShenpiActivity.this);
                }
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                swipeRefreshLayout.setRefreshing(false);
                System.out.println(s);
                progressDialog.dismiss();
                try {
                    //解析数据
                    JSONObject reply = new JSONObject(s);
                    boolean result = reply.optBoolean("result");
                    if (result) {
                        //封装数据
                        JSONArray jsonArray = reply.optJSONArray("data");
                        dataList.clear();
                        PenjinWorkflowForm workflowForm;
                        for (int j = 0; j < jsonArray.length(); j++) {
                            JSONObject jo = jsonArray.getJSONObject(j);
                            workflowForm = new PenjinWorkflowForm();
                            workflowForm.billName = jo.optString("billName");
                            workflowForm.billDate = jo.optString("date");
                            workflowForm.billNumber = jo.optString("billNumber");
                            workflowForm.auditId = jo.optString("auditId");
                            workflowForm.staffName = jo.optString("name");
                            workflowForm.staffNumber = jo.optString("staffNumber");
                            workflowForm.stafffAvatar = jo.optString("headUrl");
                            workflowForm.time = jo.optString("time");
                            workflowForm.info = jo.optString("info");
                            dataList.add(workflowForm);
                        }
                        //绑定UI
                        adapter.notifyDataSetChanged();
                        isListLoaded = true;
                    } else {
                        ToastHelper.showMessage("暂无数据", getApplicationContext());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    ToastHelper.showMessage("内容返回错误" + s, MyShenpiActivity.this);
                }

            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
            if (user.isInCompany()) {
                if (HttpUtil.isNetworkAvailable(this)) {
                    progressDialog.show();
                    launchRequest();
                } else {
                    ToastHelper.showNoNetwork(this);
                }
            } else {
                ToastHelper.showNotBindCompany(this);
            }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onRefresh() {
        if (user.isInCompany()) {
            if (HttpUtil.isNetworkAvailable(this)) {
                progressDialog.show();
                launchRequest();
            } else {
                ToastHelper.showNoNetwork(this);
            }
        } else {
            ToastHelper.showNotBindCompany(this);
        }
    }

    private void launchRequest() {
        RequestParams params = generateParams();
        try {
            httpService.postRequest(this.getApplicationContext(), HttpConstants.HOST + HttpConstants.AuditApplication, params, this.handler);
        } catch (Exception e) {
            e.printStackTrace();
            ToastHelper.showServerError(this);
            progressDialog.dismiss();
        }

    }

    private RequestParams generateParams() {
        RequestParams params = new RequestParams();
        params.put("userName", user.getPhone());
        params.put("companyId", this.company.getCompanyId());
        params.put("staffNum", this.staff.getStaffNumber());
        return params;
    }

    private class ShenpiAdapter extends BaseAdapter {
        LayoutInflater layoutInflater;

        public ShenpiAdapter(Context context) {
            layoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.item_shenpi_workflow_form, null);
                convertView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
                holder.label = (ImageView) convertView.findViewById(R.id.typeImage);
                holder.billName = (TextView) convertView.findViewById(R.id.typeName);
                holder.staffName = (TextView) convertView.findViewById(R.id.staffName);
                holder.billDate = (TextView) convertView.findViewById(R.id.billDate);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            PenjinWorkflowForm workflowForm = (PenjinWorkflowForm) getItem(position);
            holder.billName.setText(workflowForm.billName);
            holder.billDate.setText(workflowForm.billDate);
            holder.staffName.setText(workflowForm.staffName);
            return convertView;
        }

        public class ViewHolder {
            ImageView label;
            TextView billName;
            TextView staffName;
            TextView billDate;
        }
    }

}
